package slu.appli.wodtimer.swing.component.text;

import java.awt.BorderLayout;
import java.util.ArrayList;
import java.util.List;

import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.event.CaretEvent;
import javax.swing.event.CaretListener;

public class XTextStringParser
extends JPanel {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	private JTextField textField = new JTextField();
	private JLabel label = new JLabel("?");
	private List<InnerMapItem> map = new ArrayList<InnerMapItem>();
	
	public XTextStringParser() {
		super(new BorderLayout());
		this.add(this.textField,BorderLayout.NORTH);
		this.add(this.label,BorderLayout.SOUTH);
		this.textField.addCaretListener(new InnerCaretListener());
		this.showEnabledCharacters();
	}
	
	public void addMapItem(String expReg, String enabledCharacters) {
		this.map.add(new InnerMapItem(expReg, enabledCharacters));
	}
	
	private class InnerMapItem {
		private String expReg = null;
		private String enabledCharacters = null;
		
		public InnerMapItem(String expReg, String enabledCharacters) {
			super();
			this.expReg = expReg;
			this.enabledCharacters = enabledCharacters;
		}
		
		public boolean isValid(String value) {
			return value.matches(this.expReg);
		}

		public String getEnabledCharacters() {
			return enabledCharacters;
		}
		
	}

	private void showEnabledCharacters() {
		int pos = this.textField.getCaretPosition();
		if (pos < 0) return;
		
		String s = this.textField.getText();
		if (pos == 0) s="";
		else s = s.substring(0,pos);
		for (InnerMapItem mapItem : this.map) {
			if (mapItem.isValid(s)) {
				this.label.setText(String.format("%03d - %s", pos , mapItem.getEnabledCharacters()));
				break;
			}
		}
	}
	
	private class InnerCaretListener
	implements CaretListener {

		public void caretUpdate(CaretEvent ce) {
			XTextStringParser.this.showEnabledCharacters();
		}
		
	}
}
